package com.eastfair.home.service.impl;

import cn.hutool.core.bean.BeanUtil;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.home.dao.VenueReportDrawingHistoryMapper;
import com.eastfair.home.dto.VenueReportDrawingHistoryDTO;
import com.eastfair.home.entity.VenueReportDrawingHistory;
import com.eastfair.home.service.VenueReportDrawingHistoryService;
import com.eastfair.home.vo.VenueReportDrawingHistoryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 一键报馆图纸提交记录
 * </p>
 *
 * @author dq
 * @date 2022-10-31
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class VenueReportDrawingHistoryServiceImpl extends SuperServiceImpl<VenueReportDrawingHistoryMapper, VenueReportDrawingHistory> implements VenueReportDrawingHistoryService {

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<VenueReportDrawingHistory> modelList) {
        modelList.forEach(s -> s.setIsDeleted(BusinessConstant.YES));
        return R.successDef();
    }

    @Override
    protected R<Boolean> handlerSave(VenueReportDrawingHistory model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        if (model.getReportTime() == null) {
            model.setReportTime(LocalDateTime.now());
        }
        return R.successDef();
    }

    @Override
    public Page<VenueReportDrawingHistoryVO> listHistoryVO(PageParams<VenueReportDrawingHistoryDTO> pageParams) {
        log.info("listHistoryVO - 分页查询图纸提交历史VO, pageParams={}", pageParams);
        Page<VenueReportDrawingHistory> page = listHistory(pageParams);
        Page<VenueReportDrawingHistoryVO> voPage = new Page<>();
        BeanUtil.copyProperties(page, voPage);
        List<VenueReportDrawingHistory> list = page.getRecords();
        if (list == null || list.isEmpty()) {
            return voPage;
        }
        List<VenueReportDrawingHistoryVO> voList = list
                .stream()
                .map(history -> BeanUtil.toBean(history, VenueReportDrawingHistoryVO.class))
                .collect(Collectors.toList());
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public Page<VenueReportDrawingHistory> listHistory(PageParams<VenueReportDrawingHistoryDTO> pageParams) {
        Page<VenueReportDrawingHistory> pageParam = pageParams.buildPage();
        VenueReportDrawingHistoryDTO model = pageParams.getModel();
        QueryWrapper<VenueReportDrawingHistory> queryWrapper = createHistoryQueryWrapper(model);
        return page(pageParam, queryWrapper);
    }

    @Override
    public List<VenueReportDrawingHistory> listHistory(VenueReportDrawingHistoryDTO param) {
        QueryWrapper<VenueReportDrawingHistory> queryWrapper = createHistoryQueryWrapper(param);
        return list(queryWrapper);
    }

    @Override
    public VenueReportDrawingHistory getLatestSubmitHistory(Long venueReportId, Long drawingId) {
        log.info("getLatestSubmitHistory - 获取报馆中指定图纸类型的最新一条提交记录, venueReportId, drawingId");
        VenueReportDrawingHistoryDTO param = new VenueReportDrawingHistoryDTO();
        param.setVenueReportId(venueReportId);
        param.setDrawingId(drawingId);
        List<VenueReportDrawingHistory> list = listHistory(param);
        if (list == null || list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public VenueReportDrawingHistory saveVenueReportDrawingHistory(VenueReportDrawingHistoryDTO historyDTO) {
        log.info("saveVenueReportDrawingHistory - 保存报馆图纸提交历史, historyDTO={}", historyDTO);
        VenueReportDrawingHistory history = BeanUtil.toBean(historyDTO, VenueReportDrawingHistory.class);
        save(history);
        return history;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBatchAuditStatus(List<VenueReportDrawingHistoryDTO> list) {
        log.info("updateBatchAuditStatus - 批量更新提交历史的审核状态, list = {}", list);
        if (list == null || list.isEmpty()) {
            return false;
        }
        for (VenueReportDrawingHistoryDTO historyDTO : list) {
            VenueReportDrawingHistory latestSubmitHistory = getLatestSubmitHistory(historyDTO.getVenueReportId(), historyDTO.getDrawingId());
            if (latestSubmitHistory == null) {
                continue;
            }
            latestSubmitHistory.setAuditStatus(historyDTO.getAuditStatus());
            latestSubmitHistory.setAuditOpinion(historyDTO.getAuditOpinion());
            latestSubmitHistory.setAuditTime(historyDTO.getAuditTime());
            if (historyDTO.getAuditTime() == null) {
                latestSubmitHistory.setAuditTime(LocalDateTime.now());
            }
            updateById(latestSubmitHistory);
        }
        return true;
    }

    private QueryWrapper<VenueReportDrawingHistory> createHistoryQueryWrapper(VenueReportDrawingHistoryDTO model) {
        QueryWrapper<VenueReportDrawingHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(VenueReportDrawingHistory::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(model.getVenueReportId() != null, VenueReportDrawingHistory::getVenueReportId, model.getVenueReportId())
                .eq(model.getDrawingId() != null, VenueReportDrawingHistory::getDrawingId, model.getDrawingId())
                .orderByDesc(VenueReportDrawingHistory::getReportTime)
        ;
        return queryWrapper;
    }
}
